package com.xnew.menu.service;

import com.xnew.constant.Constant;
import com.xnew.menu.bean.Menu;
import com.xnew.menu.mapper.MenuMapper;
import com.xnew.resource.bean.AuResource;
import com.xnew.resource.mapper.AuResourceMapper;
import com.xnew.utils.IdUtils;
import com.xnew.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Transactional(rollbackFor = Exception.class)
public class MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private AuResourceMapper resourceMapper;

    /**
     * 查询资源信息，构建资源树结构
     *
     * @param auId
     */
    public List<Menu> createMenu(String loginName, String auId) throws Exception {
        // 原始的数据
        List<Menu> menuList = menuMapper.selectAll(loginName, auId);
        // 最后的结果
        List<Menu> menuAllList = new ArrayList<Menu>();
        // 先找到所有的一级菜单
        for (int i = 0; i < menuList.size(); i++) {
            menuList.get(i).setStatus(false);
            // 一级菜单parentId为0
            if ("0".equals(menuList.get(i).getParentId())) {
                menuList.get(i).setStatus(true);
                menuAllList.add(menuList.get(i));
            }
        }
        // 为一级菜单设置子菜单，getChild是递归调用的
        for (Menu menu : menuAllList) {
            menu.setSysMenuVoChild(this.getChild(menu.getId(), menuList));
            menu.setChildren(this.getChild(menu.getId(), menuList));
        }
        return menuAllList;
    }

    /**
     * 递归查找子菜单及资源
     *
     * @return
     */
    private List<Menu> getChild(String id, List<Menu> rootMenu) {
        List<Menu> childList = new ArrayList<>();
        for (Menu menu : rootMenu) {
//			if (!menu.getStatus()) {
            if (menu.getParentId().equals(id)) {
//					menu.setStatus(true);
                childList.add(menu);
            }
//			}
        }
        for (Menu menu : childList) {
            List<Menu> child = getChild(menu.getId(), rootMenu);
            menu.setSysMenuVoChild(child);
            menu.setChildren(child);
        }
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }

    /**
     * 新增OR修改菜单
     */
    public void addOrUpdateMenu(Menu menu) throws Exception {
        if (StringUtils.isBlank(menu.getId())) {
            addMenu(menu);
            //将当前菜单的母菜单更新为module
            menuMapper.updateResourceTypeById(menu.getParentId(), "module");
            //保存资源信息
            resourceMapper.saveResourceByMenu(menu);
        } else {
            updateMenu(menu);
            //同步修改资源信息
//			List<Menu> menus = menuMapper.selectAll("admin","");
//   //只执行一次
//			for (int i = 0; i < menus.size(); i++) {
//				Menu menu1 =  menus.get(i);
//				AuResource arEnetity = resourceMapper.selectByPrimaryKey(menu1.getId());
//				if(arEnetity!= null){
//					resourceMapper.updateByMenu(menu1);
//				}else{
//					resourceMapper.saveResourceByMenu(menu1);
//				}

//			}
            AuResource arEnetity = resourceMapper.selectByPrimaryKey(menu.getId());
            if (arEnetity != null) {
                resourceMapper.updateByMenu(menu);
            } else {
                resourceMapper.saveResourceByMenu(menu);
            }

        }
    }

    /**
     * 根据菜单信息新增菜单
     */
    public void addMenu(Menu menu) throws Exception {
        menu.setId(IdUtils.getIncreaseIdByNanoTime());
        menuMapper.insert(menu);
    }

    /**
     * 根据菜单信息修改菜单
     */
    public void updateMenu(Menu menu) throws Exception {
        menuMapper.updateByPrimaryKey(menu);
    }

    /**
     * 根据编号查询菜单信息
     */
    public Menu querySysMenuById(String id) {
        return menuMapper.selectByPrimaryKey(id);
    }

    /**
     * 根据编号删除菜单
     */
    public void deleteById(String id) {
        List<Menu> list = menuMapper.selectChildCountById(id);
        menuMapper.deleteByPrimaryKey(id);
        //判断当前菜单的母菜单下是否只有当前一个子菜单，如果只有一个删除后需要将母菜单变为url
        if (null == list || list.isEmpty() || list.size() == 1) {
            menuMapper.updateResourceTypeById(list.get(0).getParentId(), "url");
        }
    }


    /**
     * 构建行业树
     */
    public List<Map<String, Object>> createIndustryTree() throws Exception {
        // 原始的数据
        List<Map<String, Object>> industryList = menuMapper.selectIndustry();
        ;
        // 最后的结果
        List<Map<String, Object>> industryAllList = new ArrayList<Map<String, Object>>();
        // 先找到所有的一级
        for (int i = 0; i < industryList.size(); i++) {
            // 一级菜单parentId为0
            if ("0".equals(industryList.get(i).get("PID").toString())) {
                industryAllList.add(industryList.get(i));
            }
        }
        // 设置子集，getIndustryChild是递归调用的
        for (Map<String, Object> map : industryAllList) {
            map.put("children", this.getIndustryChild(map.get("DICT_CODE").toString(), industryList));
        }
        return industryAllList;
    }

    /**
     * 递归查找子集
     *
     * @return
     */
    private List<Map<String, Object>> getIndustryChild(String dictCode, List<Map<String, Object>> industryList) {
        List<Map<String, Object>> childList = new ArrayList<>();
        for (Map<String, Object> map : industryList) {
            if (map.get("PID").toString().equals(dictCode)) {
                childList.add(map);
            }
        }
        for (Map<String, Object> map : childList) {
            map.put("children", this.getIndustryChild(map.get("DICT_CODE").toString(), industryList));
        }
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }

    public HashMap<String, List<Menu>> getSysRemindMenu(String loginName, String auId) {

        // 原始的数据
        List<Menu> menuList = menuMapper.selectAll(loginName, auId);
        // 最后的结果
        List<Menu> menuAllList = new ArrayList<Menu>();
        // 修改返回的数据结构
        HashMap<String, List<Menu>> resultMap = new HashMap<>();
        // 会员档案审批首页待办提醒list
        ArrayList<Menu> auResourcesMember = new ArrayList<>();
        // 调解平台审批首页待办提醒list
        ArrayList<Menu> auResourcesMediat = new ArrayList<>();
        // 固定收益审批首页待办提醒list
        ArrayList<Menu> auResourcesFixIncome = new ArrayList<>();
        // 先找到所有的一级菜单
        // 先找到所有的一级菜单
        for (int i = 0; i < menuList.size(); i++) {
            menuList.get(i).setStatus(false);
            // 一级菜单parentId为0
            if ("0".equals(menuList.get(i).getParentId())) {
                menuList.get(i).setStatus(true);
                menuAllList.add(menuList.get(i));
            }
        }
        // 为一级菜单设置子菜单，getChild是递归调用的
        for (Menu menu : menuAllList) {
            menu.setSysMenuVoChild(this.getChild(menu.getId(), menuList));
            menu.setChildren(this.getChild(menu.getId(), menuList));
        }

        for (Menu menu : menuAllList) {
            //加入会员档案待办提醒项
            if (Constant.MEMBER_MENU.equals(menu.getId())) {
                for (Menu child : menu.getChildren()) {
                    if (Constant.MEMBER_MENU_AUDIT_AND_REPORT.equals(child.getId())) {
                        auResourcesMember.add(child);
                    }
                    if (Constant.MEMBER_MENU_INFO_REPORT.equals(child.getId())) {
                        auResourcesMember.add(child);
                    }
                }
            }
            //加入调解工作平台待办提醒项
            if (Constant.MEDIATION_MENU.equals(menu.getId())) {
                for (Menu childMenu : menu.getChildren()) {
                    if (Constant.MEDIATION_MENU_APPLY_MANAGER.equals(childMenu.getId())) {
                        List<Menu> children = menu.getChildren();
                        for (Menu childChildMenu : children) {
                            if (Constant.MEDIATION_MENU_APPLY_MANAGER_AUDIT.equals(childChildMenu.getId())) {
                                auResourcesMediat.add(childChildMenu);
                            }
                        }
                    }
                    if (Constant.MEDIATION_MENU_DISPUTE_REFERRAL.equals(childMenu.getId())) {
                        auResourcesMediat.add(childMenu);
                    }
                    if (Constant.MEDIATION_MENU_ORDINARY_MEDIATION_APPLY.equals(childMenu.getId())) {
                        for (Menu childChildMenu : childMenu.getChildren()) {
                            if (Constant.MEDIATION_MENU_ORDINARY_MEDIATION_APPLY_AUDIT.equals(childChildMenu.getId())) {
                                auResourcesMediat.add(childChildMenu);
                            }
                            if (Constant.MEDIATION_MENU_APPROVAL_OF_SECONDMENT_APPLICATION.equals(childChildMenu.getId())) {
                                auResourcesMediat.add(childChildMenu);
                            }
                            if (Constant.MEDIATION_MENU_MODIFY_THE_MEDIATOR_APPLY_AUDIT.equals(childChildMenu.getId())) {
                                auResourcesMediat.add(childChildMenu);
                            }
                        }
                    }
                    if (Constant.MEDIATION_MENU_ORDINARY_MEDIATION_HANDLE.equals(childMenu.getId())) {
                        for (Menu childChildMenu : childMenu.getChildren()) {
                            if (Constant.MEDIATION_MENU_ORDINARY_MEDIATION_HANDLE_AUDIT.equals(childChildMenu.getId())) {
                                auResourcesMediat.add(childChildMenu);
                            }
                        }
                    }
                    if (Constant.MEDIATION_MENU_ORDINARY_MEDIATION_PERIOD_MANAGE.equals(childMenu.getId())) {
                        for (Menu childChildMenu : childMenu.getChildren()) {
                            if (Constant.MEDIATION_MENU_ORDINARY_MEDIATION_PERIOD_MANAGE_AUDIT.equals(childChildMenu.getId())) {
                                auResourcesMediat.add(childChildMenu);
                            }
                        }
                    }
                }
            }
            //加入固定收益审批首页待办提醒项
            if (Constant.FIXINCOME_MENU.equals(menu.getId())) {
                for (Menu childMenu : menu.getChildren()) {
                    if (Constant.FIXINCOME_MENU_BOND_UNDER.equals(childMenu.getId())) {
                        for (Menu childChildMenu : childMenu.getChildren()) {
                            if (Constant.FIXINCOME_MENU_BOND_UNDER_SOLE_OWNER_LEADER.equals(childChildMenu.getId())) {
                                auResourcesFixIncome.add(childChildMenu);
                            }
                            if (Constant.FIXINCOME_MENU_BOND_UNDER_JOINT_MAIN_CONTRACTOR.equals(childChildMenu.getId())) {
                                auResourcesFixIncome.add(childChildMenu);
                            }
                            if (Constant.FIXINCOME_MENU_BOND_UNDER_TRUSTEE.equals(childChildMenu.getId())) {
                                auResourcesFixIncome.add(childChildMenu);
                            }
                        }
                    }
                }
            }
        }
        //装载待办数据
        resultMap.put("auResourcesMember", auResourcesMember);
        resultMap.put("auResourcesMediat", auResourcesMediat);
        resultMap.put("auResourcesFixIncome", auResourcesFixIncome);
        return resultMap;
    }
}

